package com.ctshk.rpc.cms.generator;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.Scanner;

/**
 * @author 谢诗宏
 * @description mybatis plus代码生成工具类
 * 需要根据所在服务修改相关model
 * @date 2020/12/22
 */
public class CodeGenerator {

    /**
     * 生成包所需的服务,以下MODEL常量需根据自己对应的服务改动
     */
    public static String MODEL = "cms";

    /**
     * 生成包所需的包,以下PACKAGE常量需根据自己对应的服务改动
     */
    public static String PACKAGE = "cms";

    /**
     * 生成包所需的服务完整名,以下常量不用改动
     */
    public static String PARENT_MODEL = "ctshk-cloud-" + MODEL;
    public static String RPC_MODEL = "ctshk-cloud-rpc-" + MODEL;
    public static String RPC_API_MODEL = "ctshk-cloud-rpc-" + MODEL + "-api";
    public static String SAPP_MODEL = "ctshk-cloud-sapp-" + MODEL;

    /**
     * RPC和SAPP服务路径,以下常量不用改动
     */
    public static String RPC = ".src.main.java.com.ctshk.rpc.";
    public static String SAPP = ".src.main.java.com.ctshk.sapp.";

    /**
     * 生成包所需的服务包路径,以下常量不用改动
     */
    public static String ENTITY = RPC_MODEL + RPC + PACKAGE + ".entity";
    public static String SERVICE = RPC_API_MODEL + RPC + PACKAGE + ".service";
    public static String SERVICE_IMPL = RPC_MODEL + RPC + PACKAGE + ".service.impl";
    public static String MAPPER = RPC_MODEL + RPC + PACKAGE + ".mapper";
    public static String CONTROLLER = SAPP_MODEL + SAPP + PACKAGE + ".controller";

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotBlank(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath);
        // 覆盖已有文件
        gc.setFileOverride(false);
        gc.setAuthor("LiZhiming");
        gc.setOpen(false);
        // 实体属性 Swagger2 注解
        gc.setSwagger2(true);
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://47.115.181.176:3306/ctshk-cloud-cms?useUnicode=true&useSSL=false&characterEncoding=utf8&tinyInt1isBit=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("ctshkDBdev2020!((&");
        dsc.setTypeConvert(new MySqlTypeConvert(){
            @Override
            public DbColumnType processTypeConvert(GlobalConfig globalConfig, String fiedType) {
                // tinyint转换成Integer
                if (fiedType.toLowerCase().contains("tinyint")) {
                    return DbColumnType.INTEGER;
                }
                return (DbColumnType) super.processTypeConvert(globalConfig, fiedType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        // pc.setModuleName(scanner("模块名"));
        pc.setModuleName("");
        pc.setParent(PARENT_MODEL);
        pc.setEntity(ENTITY);
        pc.setService(SERVICE);
        pc.setServiceImpl(SERVICE_IMPL);
        pc.setMapper(MAPPER);
        pc.setController(CONTROLLER);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 取消Service类继承的IService
        // 公共父类
        // strategy.setSuperServiceClass("");
        strategy.setSuperEntityClass("com.ctshk.common.model.BaseEntity");
        strategy.setSuperControllerClass("com.ctshk.common.web.support.BaseController");
        // 写于父类中的公共字段
        strategy.setSuperEntityColumns("id");
        strategy.setSuperEntityColumns("gmt_create");
        strategy.setSuperEntityColumns("gmt_modified");
        strategy.setInclude(scanner("表名（多个表用英文,隔开）").split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix("t_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}
